import { defineStore } from "pinia";
import { IProType } from "../api/home";
import { cartDel, cartGet, cartPost, cartPut } from "../api/user";
//继承商品类型
export interface ICartType extends IProType {
  num: number;
  ischeck: boolean;
  userid: string;
  objectId: string;
}
//约束state返回值类型
interface ICartState {
  list: Array<ICartType>;
}
export const useCart = defineStore("cart", {
  state: (): ICartState => {
    return {
      list: [
        // {
        //   objectId: "asdfasdf",
        //   img1: "http://img14.360buyimg.com/n1/jfs/t1/103942/14/4037/118057/5de4dfc6E5bb59781/914372d3d2d8a5a2.jpg",
        //   originprice: 99,
        //   proname: "商品名称",
        //   num: 2,
        //   ischeck: false,
        // },
        // {
        //   objectId: "asdfasddfff",
        //   img1: "http://img14.360buyimg.com/n1/jfs/t1/103942/14/4037/118057/5de4dfc6E5bb59781/914372d3d2d8a5a2.jpg",
        //   originprice: 9.9,
        //   proname: "商品名称",
        //   num: 1,
        //   ischeck: true,
        // },
      ],
    };
  },
  getters: {
    allInfo() {
      let allCheck = true;
      let allPrice = 0;
      let allNum = 0;
      this.list.forEach((item) => {
        if (!item.ischeck) {
          allCheck = false;
        }
        if (item.ischeck) {
          allPrice += item.num * item.originprice * 100;
        }
        allNum += item.num;
      });
      return { allCheck, allPrice, allNum };
    },
  },
  actions: {
    // 加入购物车
    cartAddAct(cartPro: ICartType) {
      for (let i = 0; i < this.list.length; i++) {
        if (this.list[i].proid === cartPro.proid) {
          let { objectId, num } = this.list[i];
          num++;
          //更新线上数量
          cartPut(objectId, { num }).then((res) => {
            this.list[i].num++; //修改原商品数量
          });
          return;
        }
      }
      cartPost(cartPro).then((res) => {
        console.log("新增购物车成功", res);
        cartPro.objectId = res.data.objectId; //购物车id
        this.list.push(cartPro); //新增新商品
      });
    },
    //根据用户id，从数据库请求当前用户对应的购物车数据
    async cartInitAct(userid: string) {
      let res = await cartGet(userid);
      this.list = res.data.results;
    },
    //根据购物车id，删除购物车数据
    async cartDelAct(cartid: string, idx: number) {
      cartDel(cartid).then((res) => {
        this.list.splice(idx, 1);
      });
    },
  },
  persist: {
    key: "vue-pinia-cart",
  },
});
